package com.euq.service.Impl;

import com.euq.dto.MenuDto;
import com.euq.entity.Menu;
import com.euq.mapper.MenuMapper;
import com.euq.service.MenuService;
import com.euq.utils.EuqException;
import com.euq.utils.MenuTreeBuilder;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public PageInfo<Menu> list(int page, int size) {
        PageHelper.startPage(page, size);
        List<Menu> menus = menuMapper.listAll();
        return new PageInfo<>(menus);
    }

    @Override
    public List<MenuDto> getMenuTreeNodes() {
        List<Menu> allMenus =menuMapper.listAll();
        List<MenuDto> tree = MenuTreeBuilder.buildMenuTree(allMenus);
        return tree;
    }

    @Override
    @CacheEvict(value = "userCache", allEntries = true)
    public void save(Menu menu) {
        menuSetPcode(menu);
        if(menu.getId()==0){
            menuMapper.insert(menu);
        }else {
            menuMapper.update(menu);
        }
    }

    @Override
    @CacheEvict(value = "userCache", allEntries = true)
    public void delete(Long id) {
        if(id==null){
            throw new EuqException("9999","id不能为空");
        }
        if(id<=72){
            throw new EuqException("9999","演示环境不准删除初始菜单");
        }
        Menu menu =menuMapper.findById(id);
        menuMapper.deleteSubMenu(menu.getCode());
        menuMapper.delete(id);
    }

    public void  menuSetPcode(Menu menu) {
        if (StringUtil.isEmpty(menu.getpCode()) || "0".equals(menu.getpCode())) {
            menu.setpCode("0");
            menu.setpCodes("[0],");
            menu.setLevels(1);
        } else {
            Menu pMenu = menuMapper.findByCode(menu.getpCode());
            long pLevels = pMenu.getLevels();
            menu.setpCode(pMenu.getCode());
            if (menu.getCode().equals(menu.getpCode())) {
                throw new EuqException("9999","编号与父编号重合");
            }
            menu.setLevels(pLevels + 1);
            menu.setpCodes(pMenu.getpCodes() + "[" + pMenu.getCode() + "],");
        }
    }
}
